import axios from 'axios';
import Qs from 'qs';
import Config from '@/components/common/data/Config.js';

axios.defaults.withCredentials = true;

export default class Net {
  static get(url) {
    return new Promise((resolve, reject) => {
      axios.get(url).then(res => {
        // console.log('HEADER', res.headers);
        if (res.data.status === 'ok') {
          resolve(this.successToDo(res));
        } else if (res.data.status === 'no') {
          reject(this.rejectToDo(res));
        }
      }).catch(error => {
        this.errTodo(error);
        // reject(error);
      });
    });
  }

  static post(url, paras) {
    return new Promise((resolve, reject) => {
      axios.post(url, paras).then(res => {
        if (res.data.status === 'ok') {
          resolve(this.successToDo(res));
        } else if (res.data.status === 'no') {
          reject(this.rejectToDo(res));
        }
      }).catch(error => {
        this.errTodo(error);
        // reject(error);
      });
    });
  }

  static newPost(url, paras) {
    return new Promise((resolve, reject) => {
      axios.post(url, Qs.stringify(paras))
        .then(res => {
          // console.log('HEADER', res.headers);
          // console.log(res, '2222');
          if (parseInt(res.data.err_code) === 0) {
            resolve(this.successToDo(res));
          } else if (parseInt(res.data.err_code) === 10002) {
            // console.log(111111111);
            location.href = Config.loginOld + '?return_url=' + encodeURI('http://localhost:8080/login');
          } else {
            reject(this.rejectToDo(res));
          }
        }).catch(error => {
        this.errTodo(error);
        // reject(error);
      });
    });
  }

  static rejectToDo(res) {
    alert(res.data.msg);
    return res.data.status;
  }

  // 处理成功方法
  static successToDo(res) {
    // console.log(res);
    let status = 'ok';
    let msg = res.data.msg;
    if (status === 'no') {
      alert(msg);
    } else {
      return res.data;
    }
  }

  // 新处理成功方法
  static newSuccessToDo(res) {
    delete res.data.status;
    delete res.data.msg;
    return res.data;
  }

  // 处理异常方法
  static errTodo(error) {
    let errorCode = error.response.status;
    let errorCodeFir = (error.response.status + ``).substr(0, 1);
    let msg = '';
    // console.log(error.response.status + ``);
    if (errorCodeFir === '3') {
      msg = `${errorCode}:请刷新重试!`;
      alert(msg);
    } else if (errorCodeFir === '4') {
      msg = `${errorCode}:请刷新重试!`;
      alert(msg);
    } else if (errorCodeFir === '5') {
      msg = `${errorCode}:请刷新重试!`;
      alert(msg);
    }
  }
}
